import fetch from 'dva/fetch'

let localStorage
// If we're testing, use a local storage polyfill
if (global.process && process.env.NODE_ENV === 'test') {
  localStorage = require('localStorage')
} else {
  // If not, use the browser one
  localStorage = global.window.localStorage
}

const server = {
  /**
   * Pretends to log a user in
   *
   * @param  {string} username The username of the user
   * @param  {string} password The password of the user
   */
  login (username, password) {

    return new Promise((resolve) => {
      const userExists = this.componentDidMount(username, password)
      if (userExists) {
        resolve({
          authenticated: true,
          // Fake a random token
          token: Math.random().toString(36).substring(7)
        })
      }
    })
  },

  /**
   * Pretends to log a user out and resolves
   */
  logout () {
    return new Promise(resolve => {
      localStorage.removeItem('token')
      resolve(true)
    })
  },
  /**
   *
   * @param username
   * @param passWord
   */
  componentDidMount (username, passWord) {
    const url = '/user/login'
    const param = {
      userName: username,
      passWord: passWord
    }
    fetch(url, {
      method: 'POST',
      body: JSON.stringify(param),
      headers: {
        'content-type': 'application/json'
      }
      // 请求的返回值
    }).then(function (response) {
      if (response.status === 200) {
        response.json().then(function (data) {
          console.log(data)
          if (data.success) {
            return true
          } else {
            reject(data.errorMessage)
          }
        })
      } else {
        reject('网络开小差了')
      }

    })
  }
}

export default server
